﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace Moonwish.Silverlight.Controls
{
    public class TreeViewImageHeader : Control
    {
        private Image _image;

        public static readonly DependencyProperty ImagePathProperty = DependencyProperty.Register("ImagePath", typeof (string),
                                                                                            typeof (TreeViewImageHeader),
                                                                                            new PropertyMetadata(ImagePathChanged));

        public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register("Caption",
                                                                                                typeof (string),
                                                                                                typeof (
                                                                                                    TreeViewImageHeader),
                                                                                                new PropertyMetadata(CaptionChanged));
        public static void ImagePathChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { ((TreeViewImageHeader)sender).Refresh(); }
        public static void CaptionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { ((TreeViewImageHeader)sender).Refresh(); }

        public TreeViewImageHeader()
        {
            DefaultStyleKey = typeof(TreeViewImageHeader);
        }

        /// <summary>
        /// 图片路径。
        /// </summary>
        public string ImagePath
        {
            get
            {
                return (string)GetValue(ImagePathProperty);
            }
            set
            {
                SetValue(ImagePathProperty, value);
            }
        }

        /// <summary>
        /// Header文本
        /// </summary>
        public string Caption
        {
            get
            {
                return (string) GetValue(CaptionProperty);
            }
            set
            {
                SetValue(CaptionProperty, value);
            }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _image = (Image)GetTemplateChild("Image");

            _image.Source = new BitmapImage(new Uri(ImagePath, UriKind.RelativeOrAbsolute));
        }

        private void Refresh()
        {
            if (_image != null)
            {
                _image.Source = new BitmapImage(new Uri(ImagePath, UriKind.RelativeOrAbsolute));
            }
        }
    }
}
